package com.tv.cms.authcode.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.tv.cms.authcode.model.AuthCode;
import com.tv.cms.authcode.model.AuthCodeExport;
import com.tv.cms.authcode.service.AuthCodeService;
import com.tv.cms.deviceInfo.model.DeviceInfo;
import com.tv.cms.deviceInfo.service.DeviceInfoService;
import com.tv.cms.system.account.model.Account;
import com.tv.cms.system.account.service.AccountService;
import com.tv.cms.system.admin.model.Admin;
import com.tv.cms.system.admin.service.AdminService;
import com.tv.cms.system.operator.model.Operator;
import com.tv.cms.system.operator.service.OperatorService;
import com.tv.cms.utils.ExcelUtil;
import com.tv.cms.utils.HttpUtils;
import com.tv.cms.utils.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * TODO
 *
 * @author
 * @date
 **/
@RestController
@RequestMapping("authCode")
public class AuthCodeController {

    @Value("${config.tvcms-url-status}")
    private String tvcmsUrlStatus;
    @Value("${config.tvcms-url-remark}")
    private String tvcmsUrlRemark;

    @Resource
    private AuthCodeService service;
    @Resource
    private AdminService adminService;
    @Resource
    private OperatorService operatorService;
    @Resource
    private AccountService accountService;
    @Resource
    private DeviceInfoService deviceInfoService;

    @PostMapping("list")
    public Result<Page<AuthCode>> list(@RequestBody AuthCode authCode){
        Admin admin = adminService.getById(StpUtil.getLoginIdAsInt());

        if(admin.getRoleId() == 3 || admin.getRoleId() == 5) {
            authCode.setOperatorId(admin.getOperatorId());
        }
        if(admin.getRoleId() == 2) {
            StringBuffer operatorIds = new StringBuffer();
            operatorService.dataList(operatorIds, admin.getId());
            if(StringUtils.isNotBlank(operatorIds) && operatorIds.length() > 0) {
                authCode.setOperatorIds(operatorIds.substring(0, operatorIds.length()-1));
            }
        }
        List<AuthCode> list = service.list(authCode);
        int count = service.count(authCode);
        Page<AuthCode> page =new Page<>();
        page.setRecords(list);
        page.setTotal(count);
        page.setCurrent(authCode.getPage());
        page.setSize(authCode.getLimit());
        Account account =  accountService.getOne(new QueryWrapper<Account>().eq("operator_id",admin.getOperatorId()));
        BigDecimal balance = account != null ? new BigDecimal( account.getBalance()) : new BigDecimal(0);
        page.setCountId(balance.toString());
        Result<Page<AuthCode>> result = new Result<>();
        return result.OKDATA(page);
    }

    @GetMapping("export")
    public void excelExport(@RequestParam("orderId") Integer orderId,HttpServletResponse response){
        List<AuthCodeExport> list = new ArrayList<>();
        if(orderId != null){
            AuthCodeExport authCode = new AuthCodeExport();
            authCode.setOrderId(orderId);
            list = service.exportList(authCode);
        }

        ExcelUtil.exportExcel(list, "授权码", "授权码", AuthCodeExport.class, "授权码.xls", response);
    }

    @PutMapping("updateStatus")
    public Result updateStatus(@RequestBody AuthCode authCode){
        /*try {
            Map<String,Object> map = new HashMap<>();
            map.put("id",authCode.getDeviceInfoId());
            map.put("mac",authCode.getMac());
            map.put("status",authCode.getStatus());
            String s = HttpUtils.sendPutRequest(tvcmsUrlStatus, JSON.toJSONString(map));
            JSONObject jsonObject = JSONObject.parseObject(s);
            if(!jsonObject.get("code").toString().equals("200")){
                return Result.FAILURE(jsonObject.get("message").toString());
            }
            return Result.OK();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }*/
        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.setId(authCode.getDeviceInfoId());
        deviceInfo.setStatus(authCode.getStatus());
        boolean b = deviceInfoService.updateDeviceStatus(deviceInfo);
        return b ? Result.OK() : Result.FAILURE();
    }
    @PutMapping("updateRemark")
    public Result updateRemark(@RequestBody AuthCode authCode){
       /* try {
            Map<String,Object> map = new HashMap<>();
            map.put("id",authCode.getId());
            map.put("remark",authCode.getRemark());
            String s = HttpUtils.sendPutRequest(tvcmsUrlRemark, JSON.toJSONString(map));
            JSONObject jsonObject = JSONObject.parseObject(s);
            if(!jsonObject.get("code").toString().equals("200")){
                return Result.FAILURE(jsonObject.get("message").toString());
            }
            return Result.OK();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }*/
        boolean update = service.update(authCode) > 0;
        return update ? Result.OK() : Result.FAILURE();
    }
}
